package com.msblearn.C_014;

import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;

/**
 * ForkJoinPool:把大任务切割成小任务执行。执行完会再汇总。
 * ForkJoinPool:有带返回值和不带返回值的。
 */
public class T08_ForkJoinPool {
    static int[] nums = new int[1000000];
    static final int Max_Num = 50000;
    static Random r = new Random();

    static {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = r.nextInt(100);
        }
        System.out.println("--->" + Arrays.stream(nums).sum());
    }

    static class AddTask extends RecursiveAction {
        int start, end;

        AddTask(int s, int end) {
            this.start = s;
            this.end = end;
        }


        @Override
        protected void compute() {
            if (end - start <= Max_Num) {
                long sum = 0L;
                for (int i = start; i < end; i++) {
                    sum += nums[i];
                }
                System.out.println("start:" + start + " +  end:" + end + "=" + sum);
            } else {
                int middle = start + (end - start) / 2;
                AddTask task1 = new AddTask(start, middle);
                AddTask task2 = new AddTask(middle, end);
                task1.fork();
                task2.fork();
            }
        }
    }

    static class addTaskRect extends RecursiveTask<Long>{
        int start,end;
        addTaskRect(int start,int end){
            this.start = start;
            this.end = end;
        }
        @Override
        protected Long compute() {
            if(end -start <=Max_Num){
                long sum = 0L;
                for(int i=start;i<end;i++){
                    sum += nums[i];
                }
                return sum;
            }
                int middle = start + (end - start) / 2;
                addTaskRect task1 = new addTaskRect(start, middle);
            addTaskRect task2 = new addTaskRect(middle, end);
                task1.fork();
                task2.fork();


            return task1.join()+task2.join();
        }
    }

    public static void main(String[] args) throws IOException {
        T08_ForkJoinPool pool = new T08_ForkJoinPool();
//        ForkJoinPool joinPool = new ForkJoinPool();
//        AddTask task = new AddTask(0, nums.length);
//        joinPool.execute(task);
//        System.in.read();
        ForkJoinPool fjp = new ForkJoinPool();
        addTaskRect rect = new addTaskRect(0,nums.length);
        fjp.execute(rect);
        long result = rect.join();
        System.out.println(result);
    }
}
